import { ApiCall } from "tsrpc";
import { ReqEnterSubWorld, ResEnterSubWorld } from "../../shared/protocols/masterServer/PtlEnterSubWorld";
import { DBUser } from "../DBUser";
import { masterServer } from "../../MasterServerMain";
import { TokenUtils } from "../../TokenUtils";
import { MasterServerConn } from "../MasterServer";

export async function ApiEnterSubWorld(call: ApiCall<ReqEnterSubWorld, ResEnterSubWorld>) {
    let req = call.req;
    let info = (call.conn as MasterServerConn).userInfo;

    let worldServer = masterServer.getSubWorldServer(req.subWorldId);
    if (!worldServer) {
        call.error('OUT_OF_SERVICE');
        return;
    }

    let subWorldState = worldServer.subWorldMap.get(req.subWorldId);
    if (!subWorldState) {
        return call.error("INVALID_DATA");
    }

    let needCheckPassword = subWorldState.password && subWorldState.id != info.subWorldId;

    if (needCheckPassword && subWorldState.password != req.password) {
        return call.error("INVALID_PASSWORD");
    }

    let uid = info.uid!;
    let usrToken = info.token!;
    let url = worldServer.url;
    let time = Math.floor(Date.now() / 1000);

    let token = TokenUtils.genWorldServerLoginToken(uid, url, subWorldState.id, time);

    if(subWorldState.configId != 'lobby'){
        DBUser.updateUserDataByToken(usrToken, { subWorldId: subWorldState.id });
    }

    call.succ({ subWorldId: subWorldState.id, subWorldConfigId: subWorldState.configId, worldServerUrl: url, token: token, time: time });
}